/*
 *   Copyright (c) 2018. 刘路 All rights reserved
 *   版权所有 刘路 并保留所有权利 2018.
 *   ===============================================================
 *   这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 *   使用。不允许对程序代码以任何形式任何目的的再发布。如果项目发布携带作者
 *   认可的特殊 LICENSE 则按照 LICENSE 执行，废除上面内容。请保留原作者信息。
 *   ================================================================
 *   刘路（feedback@zhoyq.com）于 2018. 创建
 *   http://zhoyq.com
 */

package com.zhoyq.helper;

import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 刘路
 */
public class StringHelper {
    private static final String HEX_STR = "0123456789ABCDEF";
    /**
     * 不支持多层嵌套的内容
     * @param str
     * @return
     * @throws Exception
     */
    public static Map<String,String> str2map(String str) throws Exception {
        try{
            str = str.replaceAll("\\{|\\}","");
            String[] aa = str.split(",");
            Map<String,String> map = new HashMap<String,String>();
            for(String aaa:aa){
                String[] aaaa = aaa.split("=");
                map.put(aaaa[0].trim(),aaaa[1].trim());
            }
            return map;
        }catch(Exception e){
            throw new Exception("格式不正确");
        }
    }

    public static byte[] hexStr2bytes(String hex){
        if(hex.length()%2 != 0) {
            hex = "0" + hex;
        }
        hex = hex.toUpperCase();
        byte[] res = new byte[hex.length()/2];
        for(int i = 0;i<res.length;i++){
            int n = i*2;
            int n_1 = n+1;
            char c = hex.charAt(n);
            char c_1 = hex.charAt(n_1);
            int buf = HEX_STR.indexOf(c);
            int buf_1 = HEX_STR.indexOf(c_1);
            res[i] = (byte)(((buf<<4)&0x000000F0)^(buf_1&0x0000000f));
        }
        return res;
    }

    public static boolean isEmpty(String str){
        return str == null || "".equals(str);
    }

    public static String fromStream(InputStream inputStream){
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder res = new StringBuilder();
        try {
            while(br.ready()){
                res.append(br.readLine()+"\n");
            }
        } catch (IOException e) {  }
        return res.toString();
    }

    public static String obj2json(Object obj){
        return JSONObject.toJSON(obj).toString();
    }
}
